﻿using ArticleClientLib;
using eslib.tools.config;
using HttpServerLib;
using HttpServerLib.Rest;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using System.Web;

namespace 软文管理
{
    internal class ArticleServer : ApiProviderBase
    {

        #region Rest API

        [Api(ApiMethod.GET, "/api")]
        public object Api0()
        {
            string msg = $"api返回,url:{Processor.FullPath}";

            if (QueryString["a"] != null) msg += $",a={QueryString["a"]}";

            return new
            {
                msg,
                val = 3.14
            };
        }


        [Api(ApiMethod.GET, "/preview/{url}")]
        public string Preview(string url)
        {
            url = HttpUtility.UrlDecode(url);

            //读取images目录
            string img = Path.Combine(url, "images");
            string[] imgs = Directory.GetFiles(img);
            string imgHtml = $"<div><img src='/{url}/main.png' /></div>";
            foreach (string i in imgs)
            {
                imgHtml += $"<div><img src='/{i}' /></div>";
            }

            string jsonPath = Path.Combine(url, "doc.json");
            ArticleJson json = GenericJsonConfig.Load<ArticleJson>(jsonPath);

            return $"<html><head> <meta content='text/html; charset=utf-8' http-equiv='Content-Type'><meta content='width=device-width,initial-scale=1,user-scalable=no' name='viewport'><meta name='apple-mobile-web-app-capable' content='yes'><meta name='apple-touch-fullscreen' content='yes'><meta name='format-detection' content='telephone=no,address=no'><meta name='apple-mobile-web-app-status-bar-style' content='white'><meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'><title>{json.title}</title></head><body>{imgHtml}</body></html>";
        }

        #endregion



        /// <summary>
        /// 软文预览
        /// </summary>
        /// <param name="article"></param>
        public static void ArticlePreview(LocalArticle article)
        {
            //预览
            string path = article.Dir;
            //移除开头的./
            if (path.Substring(0, 2) == "./") path = path.Substring(2);

            string url = $"http://127.0.0.1:{ServerConfig.Instance.port}/preview/{UrlEncoder.Default.Encode(path)}";

            //使用edge
            Process process = new Process();
            process.StartInfo.FileName = "cmd.exe";
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.CreateNoWindow = true;
            process.Start();
            process.StandardInput.WriteLine($"start msedge --kiosk {url}");
        }

    }
}
